/**
 * Created by wfle on 2018/8/19.
 */

import React, { Component } from 'react';
import {
	StyleSheet, Text, View, Image,
	TouchableOpacity, PixelRatio
} from "react-native";
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { StockTop, StockRow, StockBottomBtn } from '../../../component/Stock.js';
import { QuantityBoxModal } from '../../../component/Store';
import { cStyles } from '../storeStyle.js';
import { Common } from '../../../component/common/Common';
import ToastUtil from '../../../utils/toast'

const scale = GLOBAL.SCALE;

const quantityBoxProps = {
	onCancelPress: () => { },
	title: '盘点数量',
	onSubmitPress: () => { },
	modalVisible: false,
	quantity: 0
}
const minus = require('../../../imgs/store/minus.png');
const add = require('../../../imgs/store/add.png');
let curQuantityIndex = 0;
const sendData = {
	stockCheckReportDetailVOList: [],
};


export class StockEditPage extends Component {

	static navigationOptions = ({ navigation }) => {
		let { state, goBack } = navigation;
		const headerTitle = state.params ? state.params.title : "";
		return {
			headerTitle,
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerStyle: {
				elevation: 0,
				backgroundColor: style.color.themeColor,
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props);
		this.state = {
			loaded: true,
			status: '',
			warehouseName: '',
			dataSource: [],
			quantityModalVisible: false
		}
		this._renderItem = this._renderItem.bind(this);
		this._onCancelPress = this._onCancelPress.bind(this);
		this._onSubmitPress = this._onSubmitPress.bind(this);

		quantityBoxProps.onCancelPress = this._onCancelPress;
		quantityBoxProps.onSubmitPress = this._onSubmitPress;
	}

	componentWillMount () {

	}

	async componentDidMount () {
		const { planId } = this.props.navigation.state.params;
		sendData.planId = planId;
		const plan = await this._fetchPlanAsync(planId);
		const loaded = false;
		if (plan) {
			const { inventoryStandBookVOS, warehouseName, status } = plan;
			let dataSource = [];
			if (inventoryStandBookVOS) {
				dataSource = inventoryStandBookVOS.map((item, index) => {
					item.curQuantity = 0;
					item.index = index;
					return item;
				});
			}
			this.setState({
				dataSource,
				loaded,
				status,
				warehouseName,
			});

		} else {
			this.setState({
				loaded
			});
		}
	}

	/**
 * 返回plan
* @param {String} planId
		*/
	async _fetchPlanAsync (planId) {
		const sendData = { planId };
		const responseData = await HTTP.POST(API_GENERATE(API.GET_STOCKPLAN_DETAIL), sendData);
		return responseData;
	}

	render () {
		const { status, warehouseName, curQuantity } = this.state;
		const leftText = `仓库：${warehouseName}`;
		const rightText = `${status}`;
		const renderDataView = this.renderData();
		return (
			<View style={styles.container}>
				<View style={{ flex: 1, }}>
					<StockTop leftText={leftText} rightText={rightText} />
					{renderDataView}
				</View>
				<StockBottomBtn onPress={this._didPressSubmitBtn.bind(this)} />
				<QuantityBoxModal {...quantityBoxProps} />
			</View>
		);
	}

	/* 渲染列表 */
	renderData () {
		if (this.state.loaded) {
			return (
				<PageStatusIndex status={'loading'} />
			);
		} else {
			if (this.state.dataSource.length) {
				const { dataSource } = this.state;
				return (
					dataSource.map((inventoryStandBookVO) => {
						return this._renderItem(inventoryStandBookVO);
					})
					// <FlatList
					// 	data={this.state.dataSource}
					// 	renderItem={this._renderItem}
					// 	style={styles.flatList}
					// />
				);
			} else {
				return (
					<PageStatusIndex status={'empty'} title={''} />
				);
			}
		}

	}

	_renderItem (inventoryStandBookVO) {
		const { index, curQuantity, goodsName, onhandQuantity, batchNo, forwardQuantity, onpassQuantity, lockedQuantity } = inventoryStandBookVO;
		return (
			<View style={styles.editRow} key={index}>
				<StockRow height={30} strList={[`商品：${goodsName}`, `台账数量：${onhandQuantity}`]} style={[{ backgroundColor: '#fff', }]} />
				<View style={styles.minusCell}>
					<View style={styles.quantityLabel}><Text style={cStyles.text}>实际盘点数量：</Text></View>
					<View style={styles.quantityCell}>
						<TouchableOpacity style={styles.minus} onPress={this._countCurQuantity.bind(this, 'minus', index)} activeOpacity={0.5} >
							<Image source={minus} style={styles.cover} /></TouchableOpacity>
						<TouchableOpacity style={styles.curQuantityCell} onPress={this._didCurQuantityCellPress.bind(this, index)} activeOpacity={0.5} >
							<Text style={cStyles.textQuantity}>{curQuantity}</Text>
						</TouchableOpacity>
						<TouchableOpacity style={styles.minus} onPress={this._countCurQuantity.bind(this, 'add', index)} activeOpacity={0.5} >
							<Image source={add} style={styles.cover} /></TouchableOpacity>
					</View>
				</View>
			</View>
		);
	}

	_onCancelPress () {
		const { quantityModalVisible } = this.state;
		quantityBoxProps.modalVisible = false;
		this.setState({
			quantityModalVisible: !quantityModalVisible
		});
	}
	/**
	 * Modal 点击确定
	 */
	_onSubmitPress (quantity) {
		quantityBoxProps.modalVisible = false;
		const { dataSource, quantityModalVisible } = this.state;
		if (dataSource && dataSource.length) {
			const inventoryStandBookVO = dataSource[curQuantityIndex];
			if (inventoryStandBookVO) {

				inventoryStandBookVO.curQuantity = quantity;
			}
			dataSource[curQuantityIndex] = inventoryStandBookVO;
		}
		this.setState({
			quantityModalVisible: !quantityModalVisible,
			dataSource,
		});
	}
	/**
	 * 
	 */
	_didCurQuantityCellPress (index) {

		curQuantityIndex = index;
		const { dataSource, quantityModalVisible } = this.state;
		const inventoryStandBookVO = dataSource[index];
		if (inventoryStandBookVO) {
			let { curQuantity } = inventoryStandBookVO;
			quantityBoxProps.modalVisible = true;
			quantityBoxProps.quantity = curQuantity;
			this.setState({
				quantityModalVisible: !quantityModalVisible
			});
		}
	}
	/**
	 * 实际盘点数量加减
	 * @param {*} type 
	 * @param {*} index 
	 */
	_countCurQuantity (type, index) {
		const { dataSource } = this.state;
		if (dataSource && dataSource.length) {
			const inventoryStandBookVO = dataSource[index];
			if (inventoryStandBookVO) {
				let { curQuantity } = inventoryStandBookVO;
				if (type == 'minus') {
					if (curQuantity > 0) {
						curQuantity--;
					}
				} else if (type == 'add') {
					curQuantity++;
				}
				console.log(181, curQuantity, index);
				inventoryStandBookVO.curQuantity = curQuantity;
			}
			dataSource[index] = inventoryStandBookVO;
		}
		this.setState({
			dataSource
		});
	}

	/**
	 * 实际盘点数量加减
	 * @param {*} type 
	 * @param {*} index 
	 */
	_countBoxQuantity (type) {
		let { curQuantity } = this.state;
		if (type == 'minus') {
			if (curQuantity > 0) {
				curQuantity--;
			}
		} else if (type == 'add') {
			curQuantity++;
		}
		this.setState({
			curQuantity
		});
	}

	/**
	 * 点击‘提交’按钮
	 */
	async _didPressSubmitBtn () {
		const { dataSource } = this.state;
		sendData.stockCheckReportDetailVOList = dataSource.map(item => {
			const { goodsId, curQuantity } = item;
			return {
				goodsId,
				quantity: curQuantity
			}
		});

		const responseData = await HTTP.POST(API_GENERATE(API.APPLY_STOCK_PLAN), sendData);
		if (responseData) {
			ToastUtil.showSuccess('盘点计划已提交')
		}
	}

	// 返回上一个页面
	_goBack = () => {
		const { navigate } = this.props.navigation;
		navigate('StockTackingPage', {});
	}

}


const styles = StyleSheet.create({
	containerModal: {
		width: 375 * scale,
		height: GLOBAL.SCREEN_HEIGHT,
		backgroundColor: 'rgba(0, 0, 0, .3)',
		alignItems: 'center',
		paddingTop: 125 * scale,
	},
	quantityBox: {
		width: 271 * scale,
		height: 168 * scale,
		backgroundColor: '#fff',
		borderRadius: 13,
		alignItems: 'center',
		position: 'relative',
	},
	quantityBoxBtnCell: {
		flexDirection: 'row',
		height: 40 * scale,
		width: 271 * scale,
		borderTopColor: '#e4e4e4',
		borderTopWidth: 1 / PixelRatio.get(),
		position: 'absolute',
		bottom: 0,
	},
	quantityBoxBtn: {
		flex: 1,
		justifyContent: 'center',
		alignItems: 'center',
	},
	quantityBoxTop: {
		height: 66 * scale,
		justifyContent: 'center',
		alignItems: 'center',
	},
	quantityBoxTopText: {
		fontSize: 16 * scale,
		color: '#404040',
	},
	minusCell: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingRight: 12 * scale,
	},
	minus: {
		width: 30 * scale,
		height: 30 * scale,
	},
	cover: {
		width: '100%',
		height: '100%',
	},
	curQuantityInput: {
		borderColor: '#e4e4e4',
		borderWidth: 1 / PixelRatio.get(),
		width: 100 * scale,
		height: 30 * scale,
		fontSize: 18 * scale,
		color: '#4B4B4B'
	},
	curQuantityCell: {
		borderColor: '#e4e4e4',
		borderWidth: 1 / PixelRatio.get(),
		width: 100 * scale,
		height: 30 * scale,
		justifyContent: 'center',
		alignItems: 'center',
	},
	editRow: {
		backgroundColor: '#fff',
		paddingBottom: 16 * scale,
		marginBottom: 12 * scale,
	},
	quantityLabel: {
		flex: 1,
		paddingLeft: 12 * scale,
	},
	quantityCell: {
		flex: 1,
		flexDirection: 'row',
		justifyContent: 'space-between',
	},
	quantityWrap: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		width: 172 * scale,
		height: 30 * scale,
	},
	container: {
		flex: 1,
		backgroundColor: '#fff',
	},
	stockRow: {
		marginBottom: 12 * scale,
		backgroundColor: '#fff',
	},
	flatList: {
		backgroundColor: '#F5F5F5',
		marginTop: 12 * scale,
	},
	circleBtnCell: {
		alignItems: 'center',
		width: 375 * scale,
		height: 109 * scale,
		// position: 'absolute',
		// left: 0,
		// bottom: 0,
	},
	circleBtn: {
		width: 80 * scale,
		height: 80 * scale,
		backgroundColor: style.color.themeColor,
		justifyContent: 'center',
		alignItems: 'center',
		borderRadius: 50,
	},
	circleBtnText: {
		fontSize: 22 * scale,
		color: '#fff'
	},
});